<template>
    <div class="tabs">
        <el-tabs v-model="activeName" type="card" style="background: white;padding: 20px;height: 100%" closable
                 @tab-remove="removeTab" @tab-click="tabClick">
            <el-tab-pane
                    v-for="(item, index) in editableTabs" :index="index"
                    :key="item.name"
                    :label="item.name"
                    :name="item.name">
            </el-tab-pane>
            <router-view></router-view>
        </el-tabs>
    </div>
</template>

<script>

    export default {
        data() {
            return {
                editableTabs: [],
                routes: [],
                activeName: null
            }
        },
        methods: {
            addTab(name) {
                this.routes.forEach(rout => {
                    if (rout.name == name && this.editableTabs.indexOf(rout) == -1) {
                        //第一次的时候需要push
                        this.$router.push(rout)
                        this.editableTabs.push(rout)
                        this.activeName = name
                    } else if (rout.name == name && rout.name != this.activeName) {
                        this.$router.push(rout)
                        this.activeName = name
                    }
                })
            },
            removeTab(targetName) {
                this.editableTabs = this.editableTabs.filter(e => e.name != targetName);
                if (this.editableTabs.length > 0) {
                    let last = this.editableTabs[this.editableTabs.length - 1];
                    if (this.activeName != last.name) {
                        this.$router.push(last)
                        this.activeName = last.name
                    }
                }
            },
            tabClick(tab) {
                this.routes.forEach(route => {
                    if (route.name == tab.name) {
                        this.$router.push(route)
                    }
                })
            }
        },
        created() {
            let children = this.$router.options.routes.map(e => e.children).filter(e => e != undefined)
            children.forEach(childs => {
                childs.forEach(child => {
                    this.routes.push(child);
                    if (child.name == "数据概览") {
                        this.editableTabs.push(child)
                    }
                })
            })
        }
    }
</script>

<style lang="scss" scoped>
</style>